import React from 'react';
import {inject, observer} from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { Icon, Tools, SearchBar, TabBar } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderNoData, getTemplateBasicItem, getTemplateLinkItem,getTemplateBasicItemToHtml } from '../public';
import { compareParams } from '../../util';
import RouteModal from '../communication/RouteModal';
import BackTop from '../../public/back-to-top';
const getLabel = Tools.getLabel;

@withRouter
@inject('approvalStore')
@observer
export default class Approval extends React.Component {

  static defaultProps = {
    prefixCls: 'cowork-approval-theme',
  }
  
  constructor(props) {
    super(props);
    this.state = {
      path: props.location.pathname + '/detail',
      coworkId: '',
    }
  }

  componentDidMount() {
    const { approvalStore: { getContentData, getContentSearchCondition } } = this.props;
    getContentData();
    getContentSearchCondition();
  }

  componentWillUnmount() {
    const { approvalStore: { doContentMount, closeAllModel, doContentCancel } } = this.props;
		doContentMount();
    closeAllModel();
    doContentCancel();
  }

  toDetailPage = (e, id, path) => {
    e.stopPropagation();
    this.setState({coworkId: id});
    this.props.history.push(path);
  }

  getTemplateLinkItem = (curCls, title, name, id, path) => ( // todo: a链接点击事件
    <div className={`${curCls}-item`}>
      <div className={`${curCls}-item-left`}>{title}:</div>
      <div className={`${curCls}-item-right`}>
        <a onClick={(e) => this.toDetailPage(e, id, path)}>{name}</a>
      </div>
    </div>
  )

  getTemplateBottomItem = (curCls, type, name, clickFunc) => (
    <div className={`${curCls}-item`} onClick={clickFunc}>
      <Icon type={type} />
      {name}
    </div>
  )
  
  getTemplate = (template) => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = "cowork-template-list";
          return (
            <div className={curCls} key={data.coworkid}>
              {getTemplateBasicItemToHtml(curCls, getLabel(83238,"发表内容"), data.remarkspan)}
              {this.getTemplateLinkItem(curCls, getLabel(27519,"楼号"), `#${data.floorNumspan}`, `#${data.floorNum}`, `${this.state.path}?id=${data.coworkid}&&floor=${data.floorNum}`)}
              {getTemplateLinkItem(curCls, getLabel(344,"主题"), data.coworkidspan, data.coworkid)}
              {getTemplateBasicItem(curCls, getLabel(83209,"版块"), data.typeidspan, data.typeid)}
              {getTemplateLinkItem(curCls, getLabel(26225,"发表人"), data.discussantspan, data.discussant)}
              {getTemplateBasicItem(curCls, getLabel(23066,"发表时间"), data.timespan, data.time)}
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderSeparator = (section, index) => {
    const { approvalStore: { showContentCheck, doContentApprove, doContentDelete, contentList } } = this.props;
    const curCls = "cowork-template-bottom";
    const datas = toJS(contentList.data);
    const id = datas[index].id;
    return (
      <div className={`${curCls}-wrap`} key={`${section}_${index}`}>
        {!showContentCheck && <div className={curCls}>
          {this.getTemplateBottomItem(curCls, 'batch-approval', getLabel(142,"批准"), () => {doContentApprove({ discussIds: id })})}
          {this.getTemplateBottomItem(curCls, 'delete', getLabel(91,"删除"), () => {doContentDelete({ discussIds: id })})}
        </div>}
      </div>
    );
  }

  render(){
    const { prefixCls, approvalStore } = this.props;
    const { contentLoading, contentList, contentSearch, getContentData, updateContentAdvance, showContentCheck, contentAdValue, setStoreState,
    doContentReset, doContentDelete, doContentApprove, doContentCancel, doContentSelectAll, doContentselectNone } = approvalStore;

    let compare = true;
    if (contentSearch) {
      compare = compareParams(toJS(contentSearch.form.formData), toJS(contentSearch.form.defaultValues));
    }
    const adType = compare ? 'filter-o' : 'filter-o-hot';

    const datas = toJS(contentList.data);
    const contentSelectedKeys = toJS(contentList.selectedRowKeys);
    const buttonGroupData = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: doContentReset
      },
      { key: 'submit',
        text: getLabel(826,"确定"),
        onClick: () => {
          getContentData();
          this.props.history.go(-1);
        },
        type: 'primary',
      }
    ];

    return contentLoading ? renderLoading : (
      <div className={prefixCls}>
        <SearchBar 
          placeholder={getLabel(390654,"请输入主题")}
          value={contentAdValue}
          showExtraButton
          extraButton={[
            { key: 'advanced', show: <Icon type={adType} /> },
          ]}
          onExtraButtonClick={() => this.props.history.push(contentSearch.path)}
          onChange={val => updateContentAdvance(val)}
          onSubmit={getContentData}
        />
        <SearchAdvanced
          store={contentSearch}
          buttonGroupData={buttonGroupData}
          onChange={(condition, value) => {if(condition.domkey[0] === 'remark') { setStoreState({ contentAdValue: value }); }}}
        />
        {showContentCheck && (
          <div className="cowork-template-top">
            <span className="cowork-template-top-cancel" onClick={doContentCancel}>{getLabel(201, '取消')}</span>
            <span>{getLabel(31503,"已选择")}{contentSelectedKeys.length}{getLabel(390655,"个主题")}</span>
            {contentSelectedKeys.length !== datas.length ?
              <span className="cowork-template-top-all" onClick={doContentSelectAll}>{getLabel(556, '全选')}</span> :
              <span className="cowork-template-top-all" onClick={doContentselectNone}>{getLabel(387379,"取消全选")}</span>
            }
          </div>
        )}
        <div className={`cowork-template ${showContentCheck && 'cowork-template-checked'}`}>
          {datas.length === 0 ? renderNoData : (
             <BackTop
              visibilityHeight='200'
              modal
              target='wm-list-view-page-modal-scrollview'
            >
            <ListViewPage.Normal
              store={contentList}
              showCheck={showContentCheck}
              getTemplate={this.getTemplate}
              renderSeparator={this.renderSeparator}
              onRowClick={(selectedRowKeys) => {
                this.setState({coworkId: selectedRowKeys.coworkid});
                this.props.history.push(`${this.state.path}?id=${selectedRowKeys.coworkid}`);
              }}
            />
            </BackTop>
          )}
          {showContentCheck && (
            <TabBar>
              <TabBar.Item
                title={getLabel(83212,"批量批准")}
                key='approval'
                icon={<Icon type='batch-approval'/>}
                onPress={() => doContentApprove({ discussIds: contentSelectedKeys.join(','),dotype:'batch'})}
                disabled
              />
              <TabBar.Item
                title={getLabel(32136,"批量删除")}
                key='delete'
                icon={<Icon type='delete'/>}
                onPress={() => doContentDelete({ discussIds: contentSelectedKeys.join(','),dotype:'batch'})}
              />
            </TabBar>
          )}
        </div>
        <RouteModal/>
      </div>
    );
  }
}